#pragma once
#include <iostream>
#include <cstdio>
#include <cstdarg>
#include <string>
#include <time.h>
#include <unistd.h>
/*日志等级*/

const std::string file = "log/logMessage.txt";
enum
{
    Debug = 0, // 调试
    Info,      // 正常
    Warning,   // 告警
    Error,     // 一般错误
    Fatal,     // 严重错误
    Uknown     // 不知道
};

std::string tolevelString(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Uknown";
    }
}
std::string getTime()
{
    time_t curr = time(nullptr);
    struct tm *tmp = localtime(&curr);
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "[%d-%d-%d] [%d:%d:%d]", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday,
             tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
    return buffer;
}
/*
日志格式：日志等级 时间 pid 消息
logLeft = 日志等级 + 时间 + pid
logRight = 消息
*/
void logMessage(int level, const char*format, ...)
{
    char logLeft[1024];
    std::string level_string = tolevelString(level);
    std::string curr_time = getTime();
    snprintf(logLeft, sizeof(logLeft), "[%s] %s [%d]", level_string.c_str(), curr_time.c_str(), getpid());
     
     char logRight[1024];
     va_list p;
     va_start(p,format);
     vsnprintf(logRight,sizeof(logRight),format,p);
     va_end(p);
     //打印
      printf("%s%s\n",logLeft,logRight); 
    
    //将内容输入到文件中
//    FILE* fp = fopen(file.c_str(),"a");
//    if(fp == nullptr) 
//    {
//        std::cerr<<"fopen error"<<std::endl;
//         return;
//    }
//    fprintf(fp,"%s%s\n",logLeft,logRight);
//    fflush(fp);  //刷新文件
//    fclose(fp);
}
